package com.jeesite.modules.app.examinate.extheory;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mapper.JsonMapper;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.common.mybatis.mapper.query.QueryWhere;
import com.jeesite.modules.app.examinate.extheory.entity.AppExaminationBarbecue;
import com.jeesite.modules.app.examinate.extheory.service.AppExaminationBarbecueService;
import com.jeesite.modules.app.mockexam.theory.entity.AppExaminateTheory;
import com.jeesite.modules.app.mockexam.theory.record.entity.AppMockexamTheoryRecord;
import com.jeesite.modules.app.mockexam.theory.user.entity.TmockexamTheoryUser;
import com.jeesite.modules.app.user.entity.AppUser;
import com.jeesite.modules.app.user.service.AppUserService;
import com.jeesite.modules.app.util.time.DateUtils;
import com.jeesite.modules.app.util.wx.NioWebSocketHandler;
import com.jeesite.modules.app.util.wx.SocketMessage;
import com.jeesite.modules.conf.AppController;
import com.jeesite.modules.conf.MessageCode;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.entity.EmployeePost;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.service.EmployeeService;
import com.jeesite.modules.sys.utils.DictUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.zx.audio.bank.entity.TaudioBank;
import com.jeesite.modules.zx.audio.bank.service.TaudioBankService;
import com.jeesite.modules.zx.barbecue.signup.entity.TbarbecueSignup;
import com.jeesite.modules.zx.barbecue.signup.service.TbarbecueSignupService;
import com.jeesite.modules.zx.course.authorization.entity.TcourseAuthorization;
import com.jeesite.modules.zx.course.authorization.service.TcourseAuthorizationService;
import com.jeesite.modules.zx.examination.barbecue.entity.TexaminationBarbecue;
import com.jeesite.modules.zx.examination.barbecue.post.entity.TexaminationBarbecuePost;
import com.jeesite.modules.zx.examination.barbecue.post.service.TexaminationBarbecuePostService;
import com.jeesite.modules.zx.examination.barbecue.record.entity.TexaminationBarbecueRecord;
import com.jeesite.modules.zx.examination.barbecue.record.service.TexaminationBarbecueRecordService;
import com.jeesite.modules.zx.examination.barbecue.service.TexaminationBarbecueService;
import com.jeesite.modules.zx.examination.barbecue.user.entity.TexaminationBarbecueUser;
import com.jeesite.modules.zx.examination.barbecue.user.service.TexaminationBarbecueUserService;
import com.jeesite.modules.zx.options.bank.entity.ToptionsBank;
import com.jeesite.modules.zx.options.bank.service.ToptionsBankService;
import com.jeesite.modules.zx.picture.bank.entity.TpictureBank;
import com.jeesite.modules.zx.picture.bank.service.TpictureBankService;
import com.jeesite.modules.zx.problem.bank.entity.TproblemBank;
import com.jeesite.modules.zx.problem.bank.service.TproblemBankService;
import com.jeesite.modules.zx.question.bank.entity.TquestionBank;
import com.jeesite.modules.zx.question.bank.service.TquestionBankService;
import com.jeesite.modules.zx.reading.bank.entity.TreadingBank;
import com.jeesite.modules.zx.reading.bank.service.TreadingBankService;
import com.jeesite.modules.zx.subject.bank.entity.TsubjectBank;
import com.jeesite.modules.zx.subject.bank.service.TsubjectBankService;
import com.jeesite.modules.zx.sys.msg.push.entity.ZxMsgPush;
import com.jeesite.modules.zx.sys.msg.push.service.ZxMsgPushService;

@Controller
@RequestMapping(value = "/app/extheory/examinate/")
public class TheoryExaminationController {
	@Autowired
	private AppExaminationBarbecueService appExaminationBarbecueService;
	@Autowired
	private TexaminationBarbecueService texaminationBarbecueService;
	@Autowired
	private TbarbecueSignupService tbarbecueSignupService;
	@Autowired
	private TexaminationBarbecueRecordService texaminationBarbecueRecordService;
	@Autowired
	private TcourseAuthorizationService tcourseAuthorizationService;
	@Autowired
	private EmpUserService empUserService;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private TquestionBankService tquestionBankService;
	@Autowired
	private TexaminationBarbecueUserService texaminationBarbecueUserService;
	@Autowired
	private TexaminationBarbecuePostService texaminationBarbecuePostService;
	@Autowired
	private ZxMsgPushService zxMsgPushService;
	@Autowired
	private TaudioBankService taudioBankService;
	@Autowired
	private TreadingBankService treadingBankService;
	@Autowired
	private TpictureBankService tpictureBankService;
	@Autowired
	private TsubjectBankService tsubjectBankService;
	@Autowired
	private TproblemBankService tproblemBankService;
	@Autowired
	private ToptionsBankService toptionsBankService;
	@Autowired
	private AppUserService appUserService;
	  @ModelAttribute
	  public void alideUser(HttpServletRequest request,HttpServletResponse response){
		  System.out.println("kkkkkkkkkkkkkk");
		 String userId= request.getParameter("userId");
		 if(StringUtils.isBlank(userId)){
				AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
				return;
			}
		 String curSessionKey=request.getParameter("sessionKey");
		 if(StringUtils.isBlank(curSessionKey)){
			 AppController.renderErrorString(response, MessageCode.NOLOGIN, "或登录信息异常");
			 return;
		 }
		 AppUser appUser = appUserService.get(userId);
		 if(appUser!=null){
			 String sessionKey = appUser.getSessionKey();
			 if(StringUtils.isNotBlank(sessionKey)){
		       if(!sessionKey.equals(curSessionKey)){
		    	   AppController.renderErrorString(response, MessageCode.RELOGIN, "");
		    	   return;
		       }
			 }
		 }
		 System.out.println(userId);
	  }
	/**
	 * 查询标题和问题
	 * @param entity
	 * @param model
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "subjectList")
	public void subjectList(AppExaminationBarbecue entity, Model model,HttpServletRequest request,HttpServletResponse response) {
		List<AppExaminationBarbecue> subjList = appExaminationBarbecueService.findList(entity);
		int num=100;
		List<TquestionBank> questList=new ArrayList<>();
		for(AppExaminationBarbecue subject:subjList){
			String suId=subject.getId();
			AppExaminationBarbecue appExaminateTheory=new AppExaminationBarbecue();
			appExaminateTheory.setParentCode(suId);
			List<AppExaminationBarbecue> questionList = appExaminationBarbecueService.findList(appExaminateTheory);
			List<String> subidList=new ArrayList<>();
			for(AppExaminationBarbecue question:questionList){
				String objName = question.getObjName();
				subidList.add(objName);
			}
			Integer objType = subject.getObjType();
			switch (objType) {
			case 0://单选题
				List<TquestionBank> squetbankList = getCommonquetbankList(subidList);
				subject.setQuetbankList(squetbankList);
				break;
			case 1://多选题
				List<TquestionBank> mquetbankList = getCommonquetbankList(subidList);
				subject.setQuetbankList(mquetbankList);
				break;
			case 2://判断题
				List<TquestionBank> jquetbankList = getCommonquetbankList(subidList);
				subject.setQuetbankList(jquetbankList);
				break;
			case 3://阅读题
				List<TreadingBank> rquetbankList = getReadingBankList(subidList);
				subject.setReadingBankList(rquetbankList);
				break;
			case 4://图片题
				List<TpictureBank> pquetbankList = getPicturBankList(subidList);
				subject.setPictureBankList(pquetbankList);
				break;
			case 5://音频题
				List<TaudioBank> aquetbankList = getAudioBankList(subidList);
				subject.setAudioBankList(aquetbankList);
				break;
			case 6://案例题
				List<TquestionBank> quetbankList = getCommonquetbankList(subidList);
				subject.setQuetbankList(quetbankList);
				break;
			default:
				break;
			}
			
			
			
		}
		JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(subjList));
		AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
	}
	//从音频题库中获取数据
	private List<TaudioBank> getAudioBankList(List<String> subidList) {
		if(subidList.size()>0){			
			TaudioBank entity=new TaudioBank();
			entity.getSqlMap().getWhere().and("id", QueryType.IN, subidList);
			//查询阅读理解
			List<TaudioBank> findList = taudioBankService.findList(entity);
			for(TaudioBank audio: findList){
				String parentId=audio.getId();
				//查询题目列表
				TsubjectBank subject=new TsubjectBank();
				subject.setParentId(parentId);
				List<TsubjectBank> subjectList = tsubjectBankService.findList(subject);
				audio.setSubjectList(subjectList);
				for(TsubjectBank sb: subjectList){
					String subjId = sb.getId();
					TproblemBank problem=new TproblemBank();
					problem.setSubjectId(subjId);
					//查询问题列表
					List<TproblemBank> problemList = tproblemBankService.findList(problem);
					sb.setProblemList(problemList);
					for(TproblemBank pb:problemList){
						String pbId=pb.getId();
						ToptionsBank option=new ToptionsBank();
						option.setProblemId(pbId);
						//查询选项列表
						List<ToptionsBank> optionList = toptionsBankService.findList(option);
						for(ToptionsBank opt:optionList){
							Integer optlab = opt.getOption();
							if(optlab<6){
								String labe=DictUtils.getDictLabel("t_data_answer", optlab.toString(), "");
								String name=opt.getObjName();
								opt.setObjName(labe+"."+name);
							}
						}
						pb.setToptionsBankList(optionList);
					}
				}
			}
			return findList;
		}
		return null;
	}
	private List<TpictureBank> getPicturBankList(List<String> subidList) {
		if(subidList.size()>0){
			TpictureBank pictureBank=new TpictureBank();
			pictureBank.getSqlMap().getWhere().and("id", QueryType.IN, subidList);
			List<TpictureBank> findList = tpictureBankService.findList(pictureBank);
			for(TpictureBank picture: findList){
				String parentId=picture.getId();
				//查询题目列表
				TsubjectBank subject=new TsubjectBank();
				subject.setParentId(parentId);
				List<TsubjectBank> subjectList = tsubjectBankService.findList(subject);
				picture.setSubjectList(subjectList);
				for(TsubjectBank sb: subjectList){
					String subjId = sb.getId();
					TproblemBank problem=new TproblemBank();
					problem.setSubjectId(subjId);
					//查询问题列表
					List<TproblemBank> problemList = tproblemBankService.findList(problem);
					sb.setProblemList(problemList);
					for(TproblemBank pb:problemList){
						String pbId=pb.getId();
						ToptionsBank option=new ToptionsBank();
						option.setProblemId(pbId);
						//查询选项列表
						List<ToptionsBank> optionList = toptionsBankService.findList(option);
						for(ToptionsBank opt:optionList){
							Integer optlab = opt.getOption();
							if(optlab<6){
								String labe=DictUtils.getDictLabel("t_data_answer", optlab.toString(), "");
								String name=opt.getObjName();
								opt.setObjName(labe+"."+name);
							}
						}
						pb.setToptionsBankList(optionList);
					}
				}
			}
			return findList;
		}
		return null;
	}
	private List<TreadingBank> getReadingBankList(List<String> subidList) {
		if(subidList.size()>0){
			TreadingBank readingBank=new TreadingBank();
			readingBank.getSqlMap().getWhere().and("id", QueryType.IN, subidList);
			List<TreadingBank> findList = treadingBankService.findList(readingBank);
			for(TreadingBank reading: findList){
				String parentId=reading.getId();
				//查询题目列表
				TsubjectBank subject=new TsubjectBank();
				subject.setParentId(parentId);
				List<TsubjectBank> subjectList = tsubjectBankService.findList(subject);
				reading.setSubjectList(subjectList);
				for(TsubjectBank sb: subjectList){
					String subjId = sb.getId();
					TproblemBank problem=new TproblemBank();
					problem.setSubjectId(subjId);
					//查询问题列表
					List<TproblemBank> problemList = tproblemBankService.findList(problem);
					sb.setProblemList(problemList);
					for(TproblemBank pb:problemList){
						String pbId=pb.getId();
						String objName=pb.getObjName();
						String objAnswer = pb.getObjAnswer();
						
                        TquestionBank question=new TquestionBank();
						question.setObjName(objName);
						question.setObjType(pb.getObjType());
						question.setObjAnswer(objAnswer);
						question.setScore(pb.getScore());
						question.setAnalysis(pb.getAnalysis());
						ToptionsBank option=new ToptionsBank();
						option.setProblemId(pbId);
						//查询选项列表
						List<ToptionsBank> optionList = toptionsBankService.findList(option);
						
						for(ToptionsBank opt:optionList){
							Integer optlab = opt.getOption();
//							question.setOption1(option1);
							if(optlab<6){
								String labe=DictUtils.getDictLabel("t_data_answer", optlab.toString(), "");
								String name=opt.getObjName();
								opt.setObjName(labe+"."+name);
							}
						}
						pb.setToptionsBankList(optionList);
					}
				}
			}
			return findList;
		}
		 
		return null;
	}
	private List<TquestionBank> getCommonquetbankList(List<String> subidList) {
		if(subidList.size()>0){
			TquestionBank quebank=new TquestionBank();
			quebank.getSqlMap().getWhere().and("id", QueryType.IN, subidList);
			List<TquestionBank> quetbankList = tquestionBankService.findList(quebank);
			return quetbankList;
		}
		return null;
	}
	@RequestMapping(value = "subjectRecordList")
	public void subjectRecordList(AppExaminationBarbecue entity, Model model,HttpServletRequest request,HttpServletResponse response) {
		List<AppExaminationBarbecue> subjList = appExaminationBarbecueService.findList(entity);
		String theoryId=request.getParameter("theoryId");
		if(StringUtils.isBlank(theoryId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "理论标识");
			return;
		}
		String userId=request.getParameter("userId");
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			return;
		}
		for(AppExaminationBarbecue subject:subjList){
			String suId=subject.getId();
			AppExaminationBarbecue appExaminateTheory=new AppExaminationBarbecue();
			appExaminateTheory.setParentCode(suId);
			List<AppExaminationBarbecue> questionList = appExaminationBarbecueService.findList(appExaminateTheory);
			List<String> subidList=new ArrayList<>();
			for(AppExaminationBarbecue question:questionList){
				String objName = question.getObjName();
				subidList.add(objName);
			}
			if(subidList.size()>0){
				TquestionBank quebank=new TquestionBank();
				quebank.getSqlMap().getWhere().and("id", QueryType.IN, subidList);
				List<TquestionBank> quetbankList = tquestionBankService.findList(quebank);
				for(TquestionBank question:quetbankList){
					String id = question.getId();
					TexaminationBarbecueRecord theoryRecord=new TexaminationBarbecueRecord();
					theoryRecord.setTheoryId(theoryId);
					theoryRecord.setPostId(entity.getParentCode());
					theoryRecord.setUserId(userId);
					theoryRecord.setQuestionId(id);
					List<TexaminationBarbecueRecord> findList = texaminationBarbecueRecordService.findList(theoryRecord);
					if(findList.size()>0){
						TexaminationBarbecueRecord arecord=findList.get(0);
						String answerId = arecord.getAnswerId();
						BigDecimal score = arecord.getScore();
						question.setAnswer(answerId);
						question.setScore(score.doubleValue());
						if(StringUtils.isNotBlank(answerId)){
							String[] split = answerId.split(",");
							for(String key:split){
							    if(key.equals("1")){
							    	question.setAnswer1("1");
							    }
							    if(key.equals("2")){
							    	question.setAnswer2("2");
							    }
							    if(key.equals("3")){
							    	question.setAnswer3("3");
							    }
							    if(key.equals("4")){
							    	question.setAnswer4("4");
							    }
							    if(key.equals("5")){
							    	question.setAnswer5("5");
							    }
							}
						}
					}else{
						question.setScore(0.0);
					}
				}
				subject.setQuetbankList(quetbankList);
			}
			
		}
		JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(subjList));
		AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
	}
	/**
	 * 理论考试
	 */
	@RequestMapping(value="findExtheory")
   	public void findExtheory(AppExaminationBarbecue entity,HttpServletRequest request,HttpServletResponse response){
		String userId=request.getParameter("userId");
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			return;
		}
		EmpUser empUser = empUserService.get(userId);
		String identity = empUser.getIdentity();
		if(!identity.equals("student")){
			AppController.renderErrorString(response, MessageCode.ERROR_MESSAGE, "无权限访问");
			return;
		}
		//1.判断学员的课程
		TcourseAuthorization authorCourse=new TcourseAuthorization();
		authorCourse.setUserId(userId);
		List<TcourseAuthorization> studyCourseList = tcourseAuthorizationService.findList(authorCourse);
		if(studyCourseList!=null&&studyCourseList.size()==0){
			AppController.renderErrorString(response, MessageCode.ERROR_MESSAGE, "");
			return;
		}
		List<String> courseId=new ArrayList<>();
		
		for(TcourseAuthorization tca:studyCourseList){
			String courseId2 = tca.getCourseId();
			courseId.add(courseId2);
		}
		List<String> courseIdList=new ArrayList<>();
		//判断课程的考试岗位
		if(courseId.size()>0){
			AppExaminationBarbecue texaminationBarbecue=new AppExaminationBarbecue();
			texaminationBarbecue.setParentCode("0");
			texaminationBarbecue.getSqlMap().getWhere().and("course_id", QueryType.IN, courseId);
			List<AppExaminationBarbecue> findList2 = appExaminationBarbecueService.findList(texaminationBarbecue);
			if(findList2!=null&&findList2.size()==0){
				AppController.renderErrorString(response, MessageCode.ERROR_MESSAGE, "没需要考试的数据");
				return;
			}
			String refCode = empUser.getRefCode();
			List<String> userPost=new ArrayList<>();
			if(StringUtils.isNotBlank(refCode)){
				Employee employee = employeeService.get(refCode);
				List<EmployeePost> findEmployeePostList = employeeService.findEmployeePostList(employee);
				if(findEmployeePostList!=null&&findEmployeePostList.size()>0){
					for(EmployeePost post:findEmployeePostList){
						String postCode = post.getPostCode();
						userPost.add(postCode);
					}
				}
			}
			List<AppExaminationBarbecue> barbecueList=new ArrayList<AppExaminationBarbecue>();
			for(AppExaminationBarbecue barbecue:findList2){
				String id = barbecue.getId();
				TbarbecueSignup arg0=new TbarbecueSignup();
				arg0.setCreateBy(userId);
				arg0.setBarbecueId(id);
				List<TbarbecueSignup> findList = tbarbecueSignupService.findList(arg0);
				//判断是否已经报名
				if(findList!=null&&findList.size()>0){
					for(TbarbecueSignup ts:findList){
						String barbecueId = ts.getBarbecueId();
						Integer state = ts.getState();
						if(state==0){
							barbecue.setStateStr("已经报名正在审核");
						}else if(state==1){
							barbecue.setStateStr("报名通过审核");
						}else if(state==2){
							barbecue.setStateStr("报名数据驳回");
						}else if(state==3){
							barbecue.setStateStr("考试进行中");
						}else if(state==4){
							barbecue.setStateStr("已经完成考试");
						}
					}
				}else{
					barbecue=notSignUp(barbecue,userPost);
					if(barbecue==null){
						continue;
					}
				}
				Integer category = barbecue.getCategory();
				if(category!=null){
				    String dictLabel = DictUtils.getDictLabel("t_examination_category",category.toString(), "");
				    barbecue.setCategoryName(dictLabel);
				}
				barbecueList.add(barbecue);
			}
			JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(barbecueList));
			AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
			return;
		}else{
			AppController.renderErrorString(response, MessageCode.ERROR_MESSAGE, "");
			return;
		}
		
	}
	private AppExaminationBarbecue notSignUp(AppExaminationBarbecue barbecue,List<String> userPost){
		TexaminationBarbecuePost barbepost=new TexaminationBarbecuePost();
		barbepost.setParentId(barbecue.getId());
		List<TexaminationBarbecuePost> bpList = texaminationBarbecuePostService.findList(barbepost);
		if(bpList!=null&&bpList.size()>0){
			List<String> hasPostList=new ArrayList<>();
			for(TexaminationBarbecuePost tbp: bpList){
				String post=tbp.getPost();
				if(userPost.contains(post)){
					hasPostList.add(post);
				}
			}
			if(hasPostList.size()>0){
				return hasSignUp(barbecue);
			}else{
				//岗位不在范围不可以报名考试
				return null;
			}
		}else{
			//考试没有关联岗位可以报名考试
			return hasSignUp(barbecue);
		}
	}
	private AppExaminationBarbecue hasSignUp(AppExaminationBarbecue barbecue){
		Date signupStartDate = barbecue.getSignupStartDate();
		LocalDateTime startDateTime = DateUtils.date2LocalDateTime(signupStartDate);
		LocalDateTime now=LocalDateTime.now();
		Long betweenDays = DateUtils.betweenDays(now,startDateTime);
		if(betweenDays>0){
			barbecue.setStateStr("距离报名时间:"+betweenDays+"天");
		}else if(betweenDays==0){
			Long betweenHours = DateUtils.betweenHours(now, startDateTime);
			if(betweenHours>0){
				barbecue.setStateStr("距离报名时间:"+betweenHours+"小时");
			}else{
				Date signupEndDate = barbecue.getSignupEndDate();
				LocalDateTime endDateTime = DateUtils.date2LocalDateTime(signupEndDate);
				Long betweenDays2 = DateUtils.betweenDays(now,endDateTime);
				if(betweenDays2<0){
					barbecue.setStateStr("报名时间结束");
				}else if(betweenDays2==0){
					Long betweenHours2 = DateUtils.betweenHours(now, endDateTime);
					if(betweenHours2<0){
						barbecue.setStateStr("报名时间结束");
					}
				}
			}
		}else if(betweenDays<0){
			Date signupEndDate = barbecue.getSignupEndDate();
			LocalDateTime endDateTime = DateUtils.date2LocalDateTime(signupEndDate);
			Long betweenDays2 = DateUtils.betweenDays(now,endDateTime);
			if(betweenDays2<0){
				barbecue.setStateStr("报名时间结束");
			}else if(betweenDays2==0){
				Long betweenHours = DateUtils.betweenHours(now, endDateTime);
				if(betweenHours<0){
					barbecue.setStateStr("报名时间结束");
				}
			}
		}
		return barbecue;
	}
   	/**
	 * 理论记录
	 */
	@RequestMapping(value="examinateRecord")
   	public void examinateRecord(AppExaminationBarbecue entity,HttpServletRequest request,HttpServletResponse response){
		String userId=request.getParameter("userId");
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			return;
		}
		TexaminationBarbecueUser barbecuseUser=new TexaminationBarbecueUser();
		barbecuseUser.setUserId(userId);
		barbecuseUser.getSqlMap().getWhere().and("type", QueryType.GT, "1");
		List<TexaminationBarbecueUser> findPage2 =texaminationBarbecueUserService.findList(barbecuseUser);
		for(TexaminationBarbecueUser barUser:findPage2){
			String theoryId = barUser.getTheoryId();
			if(StringUtils.isNotBlank(theoryId)){
			  AppExaminationBarbecue appExaminationBarbecue = appExaminationBarbecueService.get(theoryId);
			  String objName = appExaminationBarbecue.getObjName();
			  barUser.setTheoryName(objName);
			}
			String postId = barUser.getPostId();
			if(StringUtils.isNotBlank(postId)){
				  AppExaminationBarbecue appExaminationBarbecue = appExaminationBarbecueService.get(postId);
				  String objName = appExaminationBarbecue.getObjName();
				  barUser.setPostName(objName);
			}
		}
		JSONArray json=JSONObject.parseArray(JsonMapper.toJson(findPage2));
		AppController.renderSuccessObject(response, json, MessageCode.SUCCESS_ACK);
	}
	/**
	 * signuped
	 */
	@RequestMapping(value="signuped")
   	public void signuped(AppExaminationBarbecue entity,HttpServletRequest request,HttpServletResponse response){
		String userId=request.getParameter("userId");
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			return;
		}
		TbarbecueSignup arg0=new TbarbecueSignup();
		arg0.setCreateBy(userId);
		List<Integer> states=new ArrayList<>();
		states.add(0);
		states.add(1);
		states.add(3);
		arg0.getSqlMap().getWhere().and("state", QueryType.IN, states);
		List<TbarbecueSignup> findList = tbarbecueSignupService.findList(arg0);
		List<String> list=new ArrayList<String>();
	    Map<String, TbarbecueSignup> map=new HashMap<>();
		for(TbarbecueSignup ts:findList){
			String barbecueId = ts.getBarbecueId();
			list.add(barbecueId);
			map.put(barbecueId, ts);
		}
		List<AppExaminationBarbecue> findList2 = new ArrayList<>();
		if(list.size()>0){
			entity.getSqlMap().getWhere().and("id", QueryType.IN, list);
			findList2 = appExaminationBarbecueService.findList(entity);
			for(AppExaminationBarbecue abb:findList2){
				String id = abb.getId();
				TbarbecueSignup tbarbecueSignup = map.get(id);
				abb.setBarbecueSignup(tbarbecueSignup);
				Date barbecueStartDate = abb.getBarbecueStartDate();
				if(barbecueStartDate!=null){
					LocalDateTime starLocal = DateUtils.date2LocalDateTime(barbecueStartDate);
					LocalDateTime now=LocalDateTime.now();
					Long betweenMinutes = DateUtils.betweenMinutes(now, starLocal);
					if(betweenMinutes>0){
						if(betweenMinutes>60){
							Long betweenHours = DateUtils.betweenHours(now, starLocal);
							if(betweenHours>24){
								Long betweenDays = DateUtils.betweenDays(now, starLocal);
								abb.setStartTimeOf("距离考试开始时间:"+betweenDays+"天");
							}else{
								abb.setStartTimeOf("距离考试开始时间:"+betweenHours+"小时");
							}
						}else{
							abb.setStartTimeOf("距离考试开始时间:"+betweenMinutes+"分钟");
						}
					}else{//考试结束时间
						Date barbecueEndDate = abb.getBarbecueEndDate();
						if(barbecueEndDate!=null){
							LocalDateTime endLocal = DateUtils.date2LocalDateTime(barbecueEndDate);
							Long betweenMinutesEnd = DateUtils.betweenMinutes(now, endLocal);
							if(betweenMinutesEnd>0){
								abb.setEndTimeOf("距离考试结束时间:"+betweenMinutesEnd);
								abb.setOngoing("考试进行中");
								abb.setUpEndTime(betweenMinutesEnd);
							}else{
								abb.setEndTimeOf("考试结束");
							}
						}
						
					}
				}
			}
		}
		JSONArray json=JSONObject.parseArray(JsonMapper.toJson(findList2));
		AppController.renderSuccessObject(response, json, MessageCode.SUCCESS_ACK);
	}
	/**
	 * handsOn
	 */
	@RequestMapping(value="handsOn")
   	public void handsOn(AppExaminationBarbecue entity,HttpServletRequest request,HttpServletResponse response){
		String userId=request.getParameter("userId");
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			return;
		}
	}
	/**
	 * 未报名、已报名
	 * @param entity
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="findPage")
   	public void findPage(AppExaminationBarbecue entity,HttpServletRequest request,HttpServletResponse response){
		entity.setPage(new Page<>(request, response));
		entity.setStatus("0");
		String userId=request.getParameter("userId");
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			return;
		}
		String signup=request.getParameter("signup");
		if(StringUtils.isBlank(signup)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "类型");
			return;
		}
		TbarbecueSignup arg0=new TbarbecueSignup();
		arg0.setCreateBy(userId);
		
		Page<AppExaminationBarbecue> findPage =new Page<>(request, response);
		if(signup.equals("1")){//未报名
			List<TbarbecueSignup> findList = tbarbecueSignupService.findList(arg0);
			List<String> list=new ArrayList<String>();
			for(TbarbecueSignup ts:findList){
				String barbecueId = ts.getBarbecueId();
				list.add(barbecueId);
			}
			entity.getSqlMap().getWhere().and("id", QueryType.NOT_IN, list);
			LocalDateTime day_start=LocalDateTime.now();
			entity.getSqlMap().getWhere().and("barbecue_start_date", QueryType.GTE, day_start);
			findPage = appExaminationBarbecueService.findPage(entity);
			
		}else if(signup.equals("2")){//已报名
			List<Integer> states=new ArrayList<>();
			states.add(0);
			states.add(1);
			states.add(3);
			arg0.getSqlMap().getWhere().and("state", QueryType.IN, states);
			List<TbarbecueSignup> findList = tbarbecueSignupService.findList(arg0);
			List<String> list=new ArrayList<String>();
		    Map<String, TbarbecueSignup> map=new HashMap<>();
			for(TbarbecueSignup ts:findList){
				String barbecueId = ts.getBarbecueId();
				list.add(barbecueId);
				map.put(barbecueId, ts);
			}
			if(list.size()>0){
				entity.getBarbecueSignup().setCreateBy(userId);
				entity.getSqlMap().getWhere().and("id", QueryType.IN, list);
				findPage = appExaminationBarbecueService.findPage(entity);
				for(AppExaminationBarbecue abb:findPage.getList()){
					String id = abb.getId();
					TbarbecueSignup tbarbecueSignup = map.get(id);
					abb.setBarbecueSignup(tbarbecueSignup);
				}
			}
		}else if(signup.equals("4")){//考试记录
			arg0.setState(4);
			arg0.setPage(new Page<>(request, response));
			Page<TbarbecueSignup> findPage2 = tbarbecueSignupService.findPage(arg0);
			JSONObject json=JSONObject.parseObject(JsonMapper.toJson(findPage2));
			AppController.renderSuccessObject(response, json, MessageCode.SUCCESS_ACK);
			return;			
		}
		JSONObject json=JSONObject.parseObject(JsonMapper.toJson(findPage));
		AppController.renderSuccessObject(response, json, MessageCode.SUCCESS_ACK);
	}
	/**
	 * 针对不同的岗位进行查询
	 * @param entity
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="headList")
	public void headList(AppExaminationBarbecue entity,HttpServletRequest request,HttpServletResponse response){
		String userId=request.getParameter("userId");
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			return;
		}
//		EmpUser empUser = empUserService.get(userId);
//		List<String> postList=new ArrayList<>();
//		if(empUser!=null){
//			Employee employee = empUser.getEmployee();
//			List<EmployeePost> findEmployeePostList = employeeService.findEmployeePostList(employee);
//			for(EmployeePost post:findEmployeePostList){
//				String postCode = post.getPostCode();
//				postList.add(postCode);
//			}
//		}
//		if(postList!=null&&postList.size()>0){
			
//			TexaminationBarbecuePost texamination=new TexaminationBarbecuePost();
//			texamination.setParentId(entity.getParentCode());
//			texamination.getSqlMap().getWhere().and("post", QueryType.IN, postList);
//			List<TexaminationBarbecuePost> barPostList=texaminationBarbecuePostService.findList(texamination);
//			List<String> idList=new ArrayList<>();
//			for(TexaminationBarbecuePost bpost:barPostList){
//				String barbecueId = bpost.getBarbecueId();
//				idList.add(barbecueId);
//			}
//			entity.getSqlMap().getWhere().and("id",QueryType.IN, idList);
//			List<AppExaminationBarbecue> findList = appExaminationBarbecueService.findList(entity);
//			int over=0;
//			int size=findList.size();
//			for(AppExaminationBarbecue barbe:findList){
//				TexaminationBarbecueUser barbeUser=new TexaminationBarbecueUser();
//				barbeUser.setTheoryId(entity.getParentCode());
//				barbeUser.setUserId(userId);
//				barbeUser.setPostId(barbe.getId());
//				List<TexaminationBarbecueUser> findList2 = texaminationBarbecueUserService.findList(barbeUser);
//				if(findList2!=null&&findList2.size()>0){
//					Integer type=findList2.get(0).getType();
//					if(type>1){over+=1;}
//					barbe.setState(type);
//				}else{
//					barbe.setState(0);
//				}
//			}
//			if(over==size){
//				TbarbecueSignup barbsig=new TbarbecueSignup();
//				barbsig.setBarbecueId(entity.getParentCode());
//				barbsig.setCreateBy(userId);
//				List<TbarbecueSignup> findList2 = tbarbecueSignupService.findList(barbsig);
//				for(TbarbecueSignup signup:findList2){
//					signup.setState(4);
//					tbarbecueSignupService.update(signup);
//				}
//			}
		AppExaminationBarbecue bar=appExaminationBarbecueService.get(entity.getId());
		JSONObject parseArray = JSONObject.parseObject(JsonMapper.toJson(bar));
		AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
//		}else{
//			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "岗位标识不存在");
//			return;
//		}
	}
	@RequestMapping(value="findList")
	public void findList(AppExaminationBarbecue entity,HttpServletRequest request,HttpServletResponse response){
		List<AppExaminationBarbecue> findList = appExaminationBarbecueService.findList(entity);
		JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(findList));
		AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
	}
	
	@RequestMapping(value="tfindList")
	public void tfindList(TexaminationBarbecue entity,HttpServletRequest request,HttpServletResponse response){
		List<TexaminationBarbecue> findList = texaminationBarbecueService.findList(entity);
		TexaminationBarbecueRecord tbr=null;
		String userId=request.getParameter("userId");
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户表示");
			return;
		}
		for(TexaminationBarbecue model: findList){
			String id = model.getId();
			tbr=new TexaminationBarbecueRecord();
			tbr.setQuestionId(id);
			tbr.setUserId(userId);
			List<TexaminationBarbecueRecord> findList2 = texaminationBarbecueRecordService.findList(tbr);
			for(TexaminationBarbecueRecord tbb: findList2){
				BigDecimal score = tbb.getScore();
				if(score==null){
					model.setQuestionScore(new BigDecimal(0));
				}else{
				  model.setQuestionScore(score);
				}
			}
		}
		JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(findList));
		AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
	}
	@RequestMapping(value = "options")
	public void options(AppExaminationBarbecue entity,HttpServletRequest request,HttpServletResponse response) {
		String parentCode = entity.getParentCode();
		if(StringUtils.isBlank(parentCode)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "上级节点");
			return;
		}
		String userId=request.getParameter("userId");
        if(StringUtils.isBlank(userId)){
        	AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户信息");
			return;
		}
        List<AppExaminationBarbecue> findList = appExaminationBarbecueService.findList(entity);
        TexaminationBarbecueRecord record=new TexaminationBarbecueRecord();
        record.setQuestionId(parentCode);
		record.setUserId(userId);
		List<TexaminationBarbecueRecord> list = texaminationBarbecueRecordService.findList(record);
		TexaminationBarbecueRecord amtr=null;
		Map<String, String> map=new HashMap<>();
		if(list!=null&&list.size()>0){
			amtr=list.get(0);
			String answerId= amtr.getAnswerId();
	        Integer type=amtr.getQuestionType();
	        switch (type) {
	        case 0:
				map.put(answerId, "true");
				break;
			case 1:
				String[] split = answerId.split(",");
				for(String key:split){
					map.put(key, "true");
				}
				break;
			case 2:				
				 map.put(parentCode, answerId);				
				break;
			default:
				break;
	        }
		}
		for(AppExaminationBarbecue model: findList){
			String id = model.getId();
			if(map.containsKey(id)){
				model.setChecked(true);
			}	
		}
		JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(findList));
		AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
	}
	@RequestMapping(value = "compute")
	public void compute(AppExaminationBarbecue entity,HttpServletRequest request,HttpServletResponse response) {
		String userId=request.getParameter("userId");
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户信息");
			return;
		}
		String theoryId=request.getParameter("theoryId");
        if(StringUtils.isBlank(theoryId)){
        	AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "理论标识");
			return;
		}
        String signupId=request.getParameter("signupId");
        if(StringUtils.isBlank(signupId)){
        	AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "报名信息不存在");
			return;
		}
        String postId=request.getParameter("postId");
        if(StringUtils.isBlank(postId)){
        	AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "岗位类别");
			return;
        }
        TexaminationBarbecueRecord model=new TexaminationBarbecueRecord();
        model.setTheoryId(theoryId);
        model.setUserId(userId);
        model.setPostId(postId);
        List<TexaminationBarbecueRecord> findList = texaminationBarbecueRecordService.findList(model);
        BigDecimal success=new BigDecimal(0);
        int error=0;
        int record=findList.size();
        if(findList!=null&&findList.size()>0){
        	for(TexaminationBarbecueRecord amtr:findList){
        		BigDecimal score = amtr.getScore();
        		if(score==null){
        			score=new BigDecimal(0.0);
        		}
        		success=success.add(score);
        	}
        }
        
        String theoryUserId=request.getParameter("theoryUserId");
        if(StringUtils.isNotBlank(theoryUserId)){
        	TexaminationBarbecueUser ttu=texaminationBarbecueUserService.get(theoryUserId);
        	Integer type = ttu.getType();
        	if(type>1){
        		JSONObject obj=new JSONObject();
                obj.put("success", success);
                obj.put("error", error);
                obj.put("record", record);
                AppController.renderSuccessObject(response, obj, MessageCode.SUCCESS_ACK);
                return;
        	}
        	ttu.setId(theoryUserId);
        	ttu.setScore(success.doubleValue());
    		if(success.doubleValue()>=85){
    			ttu.setType(2);
    			try {
					 ZxMsgPush zxMsgPush=new ZxMsgPush();
					 zxMsgPush.setSendDate(new Date());
					 zxMsgPush.setReceiveCode(userId);
					 zxMsgPush.setMsgTitle("积分获取");
					 zxMsgPush.setMsgContent("恭喜！出色的完成本次考试获的“5积分”的奖励");
					 zxMsgPush.setReadStatus("0");
					 zxMsgPushService.save(zxMsgPush);
					 String sendUserCode = zxMsgPush.getReceiveCode();
					 ZxMsgPush msgpush=new ZxMsgPush();
					 msgpush.setReceiveCode(sendUserCode);
					 msgpush.setReadStatus("0");
					 long findCount = zxMsgPushService.findCount(msgpush);
					 SocketMessage sm=new SocketMessage();
					 sm.setType("courseinfo");
					 sm.setNum(findCount);
					 sm.setUserId(sendUserCode);
					 NioWebSocketHandler.sendMessage(JsonMapper.toJson(sm));
				} catch (Exception e) {
					e.printStackTrace();
				}
    		}else{
        	    ttu.setType(3);
    		}
    		texaminationBarbecueUserService.update(ttu);
    		
    		
        }
        JSONObject obj=new JSONObject();
        obj.put("success", success);
        obj.put("error", error);
        obj.put("record", record);
        AppController.renderSuccessObject(response, obj, MessageCode.SUCCESS_ACK);
	}
}
